package com.chii.image.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class FtpClientUtil {
    private Logger logger = LogManager.getLogger(FtpClientUtil.class);
    private static FTPClient ftpClient;
    //生成时间
    private static Long startime = 0L;

    @Value("${ftp.path}")
    private String path;
    @Value("${ftp.url}")
    private String url;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;

    public void creat() {
        Long now = System.currentTimeMillis();
        if (ftpClient != null && now - startime < ftpClient.getConnectTimeout()) {
            return;
        }
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(url);
            ftpClient.login(username, password);
            //设置文件传输模式为二进制，可以保证传输的内容不会被改变
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //设置连接超时时间
            ftpClient.setConnectTimeout(1000 * 30);
            //设置ftp字符集
            ftpClient.setControlEncoding("utf-8");
            //设置被动模式，文件传输端口设置
            ftpClient.enterLocalPassiveMode();
            // 设置上传目录 must
            ftpClient.changeWorkingDirectory(path);
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                logger.error("connect ftp {} failed", url);
                ftpClient.disconnect();
            }
            logger.info("replyCode==========={}", replyCode);
        } catch (IOException e) {
            logger.error("connect fail ------->>>" + e.getCause());
        }
        FtpClientUtil.startime = System.currentTimeMillis();

    }


    public boolean upload(MultipartFile uploadFile, String fileName) throws IOException {
        boolean result = false;
        try {
            InputStream is = uploadFile.getInputStream();
            result = ftpClient.storeFile(path + fileName, is);
            is.close();
        } catch (IOException e) {
            result = false;
            e.printStackTrace();
        }
        System.out.println("上传完成。。。");
        return result;
    }

    public boolean upload(InputStream uploadFile, String fileName) throws IOException {
        boolean result = false;
        try {
            result = ftpClient.storeFile(path + fileName, uploadFile);
            uploadFile.close();
        } catch (IOException e) {
            result = false;
            e.printStackTrace();
        }
        System.out.println("上传完成。。。");
        return result;
    }

    public static void closeConnect() {
        try {
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
